package com.uuj.project.net;

import com.uuj.project.base.BaseResponse;
import com.uuj.project.utils.ExceptionHandle;

import org.reactivestreams.Publisher;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * ProjectName:    ok_rxjava_retrofit
 * Package:        com.uuj.project.net
 * ClassName:      RxUtil
 * Description:    描述
 * Author:         张继
 * CreateDate:     2019/8/8 11:45
 * UpdateUser:     更新者
 * UpdateDate:     2019/8/8 11:45
 * UpdateRemark:   更新说明
 * Version:        1.0
 */
public final class RxUtil {
    private RxUtil() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 切换线程
     *
     * @param <T> 类型
     * @return 返回FlowableTransformer实例对象
     */
    static <T> FlowableTransformer<T, T> applySchedulers() {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 切换线程
     *
     * @param <T> 类型
     * @return 返回FlowableTransformer实例对象
     */
    static <T> FlowableTransformer<BaseResponse<T>, T> handleResult() {
        return upstream -> upstream.flatMap(response -> {
            if (response.success()) {
                return createData(response.getData());
            } else {
                // 如果不正确 丢给错误代码统一处理类
                ExceptionHandle.ServerException exception = new ExceptionHandle.ServerException();
                exception.code = response.getResult();
                return Flowable.error(exception);
            }
        });
    }

    private static <T> Flowable<T> createData(T data) {
        return Flowable.create(emitter -> {
            try {
                emitter.onNext(data);
                emitter.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }, BackpressureStrategy.BUFFER);
    }


}
